var data_key; //树上需要展示的name属性
var id_key; //id的字段
var pId_key; //根节点的字段
var root_pid; //根节点的值
var autoParam; //需要传入到后台的值 多个以，隔开
var url; //需要请求的后台url
var treeId; //树id
var settings; //配置settings文件 不用传入
var searchId; //树搜索确定的按钮
var searchInput; //树搜索的input框
var okBtn; //确定选择节点的按钮
var closeBtn; //关闭树的按钮
var showInput; //回显数据的input
var showBtn; //展示div的按钮
var showDiv; //展示div的id
var isMulitSelect; //是否是多选
var mulitNum=0;
var iconPathPrefix;
//允许返回的最大条数，过多前端渲染会崩溃，故控制到800条数量，
//可以适当调整 不建议大于1000
var maxSearchResult=800;
var isAutoAsync=true;
var DAM={
	_settings_data_key : function(param){
		data_key=param;
	},
	_settings_data_simpleData_idKey:function(param){
		id_key=param;
	},
	_settings_data_simpleData_pIdKey:function(param){
		pId_key=param;
	},
	_settings_data_simpleData_rootPId:function(param){
		root_pid=param;
	},
	_async_autoParam:function(param){
		autoParam=param.split(",");
	},
	_async_url:function(param){
		url=param;
	},
	_treeId:function(param){
		treeId=param;
	},
	//设置紧随tree的搜索框的按钮id
	_searchId:function(param){
		searchId=param;
	},
	//设置紧随tree的搜索框
	_searchInput:function(param){
		searchInput=param;
	},
	//设置是否为自动异步加载 默认为true
	_isAutoAsync:function(param){
		isAutoAsync=param;
	},
	//设置tree下方ok键的id
	_okBtn:function(param){
		okBtn=param;
	},
	//设置tree下方关闭键的id
	_closeBtn:function(param){
		closeBtn=param;
	},
	//设置需要回显树上选中节点到指定的显示框的id
	_showInput:function(param){
		showInput=param;
	},
	//设置需要显示tree的按钮id
	//因为默认tree不显示
	_showBtn:function(param){
		showBtn=param;
	},
	//设置tree所在div的id
	_showDiv:function(param){
		showDiv=param;
	},
	//设置是否为多选tree 默认为false
	_isMulitSelect:function(param){
		isMulitSelect=param;
	},
	//如果设置为多选，必须设置此属性
	//此属性作为一次性最多选中X个节点
	//X最好不要大于100 否则会影响效率
	_mulitNum:function(param){
		mulitNum=param;
	},
	_iconPathPrefix:function(param){
		iconPathPrefix=param;
	},
	//dataKey:dataKey 需要显示到树节点上的值得key
	//idKey : id的key
	//pIdKey : pid 的key
	//rootPid : 根节点pid的值
	//autoParam: 提交到后台的值 多个值之间用"，"隔开
	//url ： 需要提交到后台的url
	//treeId:树的id  前端展示的树
	_initAutoAsync:function(dataKey,idKey,pIdKey,rootPid,autoParam,url,treeId){
		console.log("method is :AutoAsync. init params");
		DAM._settings_data_key(dataKey);
		DAM._settings_data_simpleData_idKey(idKey);
		DAM._settings_data_simpleData_pIdKey(pIdKey);
		DAM._settings_data_simpleData_rootPId(rootPid);
		DAM._async_autoParam(autoParam);
		DAM._async_url(url);
		DAM._treeId(treeId);
		var autoParams=autoParam.split(",");
		settings = {
				view: {
					selectedMulti: false
				},
				data: {
					key:{name:data_key},
					simpleData: {
						enable: true,
						idKey: id_key,
			            pIdKey: pId_key,
			            rootPId: root_pid
					}
				},
				check: {
					enable: isMulitSelect
				},
				async: {
			        enable: true,
			        autoParam: autoParams,//异步加载参数（即向后台传送节点的这三个属性值）
			        url:url,
			        dataType:"json",
			        dataFilter:  asyncResponseData
			    },
				callback: {
					beforeAsync: DAM_beforeAsync,
					onAsyncSuccess : DAM_zTreeOnAsyncSuccess//树加载成功时的回调函数
					,onClick:DAM_zTreeOnClick
				}
			};
	},
	//dataKey:dataKey 需要显示到树节点上的值得key
	//idKey : id的key
	//pIdKey : pid 的key
	//rootPid : 根节点pid的值
	//autoParam: 提交到后台的值 多个值之间用"，"隔开
	//url ： 需要提交到后台的url
	//treeId:树的id  前端展示的树
	_initAsync:function(dataKey,idKey,pIdKey,rootPid,autoParam,url,treeId){
		console.log("method is :Async. init params");
		DAM._settings_data_key(dataKey);
		DAM._settings_data_simpleData_idKey(idKey);
		DAM._settings_data_simpleData_pIdKey(pIdKey);
		DAM._settings_data_simpleData_rootPId(rootPid);
		DAM._async_autoParam(autoParam);
		DAM._async_url(url);
		DAM._treeId(treeId);
		var autoParams=autoParam.split(",");
		settings = {
				view: {
					selectedMulti: false
				},
				data: {
					key:{name:data_key},
					simpleData: {
						enable: true,
						idKey: id_key,
			            pIdKey: pId_key,
			            rootPId: root_pid
					}
				},
				check: {
					enable: isMulitSelect
				},
				async: {
			        enable: true,
			        autoParam: autoParams,//异步加载参数（即向后台传送节点的这三个属性值）
			        url:url,
			        dataType:"json",
			        dataFilter:  asyncResponseData
			    },
				callback: {
					onAsyncSuccess : DAM_zTreeOnAsyncSuccessAsync//树加载成功时的回调函数
					,onClick:DAM_zTreeOnClickAsync
				}
			};
	}
}
var zNodes;
var curAsyncCount=0;
function DAM_beforeAsync() {
	curAsyncCount++;
}
function asyncResponseData(treeId, parentNode, responseData) {
    if (responseData) {
      for(var i =0; i < responseData.length; i++) {
       // responseData[i].icon = iconPathPrefix + responseData[i].icon;
      }
    }
    return responseData;
}
//单击事件事件
function DAM_zTreeOnClickAsync(event, treeId, treeNode) {
	var treeObj =  $.fn.zTree.getZTreeObj(""+treeId+"");
	DAM_zTreeOnAsyncSuccessAsync(event, treeId, treeNode);
	if(treeNode.open){
		treeObj.expandNode(treeNode, false, false, false);
	}else{
		treeObj.expandNode(treeNode, true, false, false);
	}
}
//单击事件事件
function DAM_zTreeOnClick(event, treeId, treeNode) {
	var treeObj =  $.fn.zTree.getZTreeObj(""+treeId+"");
	if(treeNode.open){
		treeObj.expandNode(treeNode, false, false, false);
	}else{
		treeObj.expandNode(treeNode, true, false, false);
	}
}
var asyncForAll = false;
var curStatus='init';
function asyncLoad(nodes){
	if(!nodes) return;
	if(nodes.length>0){
		curStatus='async';
		var zTree =  $.fn.zTree.getZTreeObj(""+treeId+"");
		for(var i=0;i<nodes.length;i++){
			if(nodes[i].isParent && nodes[i].zAsync){
				asyncLoad(nodes[i].children);
			}else{
				zTree.reAsyncChildNodes(nodes[i], "", true);
			}
		}
	}
}

function DAM_zTreeOnAsyncSuccess(event, treeId, treeNode, msg){
	curAsyncCount--;
 	//console.log("异步加载子节点");
 	if(curStatus=='init'){
 		//初始化
 		var treeObj =  $.fn.zTree.getZTreeObj(""+treeId+"");
     	 //获取父节点为ROOT的节点，若节点没有加载子节点，则强制加载子节点
 		var rootNodes = treeObj.getNodesByParam(""+pId_key+"", ""+root_pid+"", null);
 		//循环判断该节点是否已加载子节点，是则进入下一次循环，否则加载子节点，确保加载子节点只加载一次，若加载多次会影响效率
	        for(var i=0; i<rootNodes.length; i++){
	            if(rootNodes[i].zAsync == false){
	            	treeObj.reAsyncChildNodes(rootNodes[i], "",true);    
	            }else{
	            	if(rootNodes[i].children.length>0){
	            		asyncLoad(rootNodes[i].children);
	            	}
	            }
	        }//end for 
 	}else{
 		asyncLoad(treeNode.children);
 	}
 	if (curAsyncCount <= 0) {
		if (curStatus != "init" && curStatus != "") {
			asyncForAll = true;
			//console.log("数据加载完成");
			$("#"+searchInput+"").removeAttr("disabled");
			$("#"+searchId+"").removeAttr("disabled");
			$("#"+searchInput+"").attr("placeholder","请输入关键字，进行查询！");
		}
		curStatus = "";
	}
}//end func


function DAM_zTreeOnAsyncSuccessAsync(event, treeId, treeNode, msg){
 	//console.log("异步加载子节点");
 	//初始化
	var treeObj =  $.fn.zTree.getZTreeObj(treeId);
 	 //获取父节点为ROOT的节点，若节点没有加载子节点，则强制加载子节点
 	var rootNodes;
 	if(treeNode==undefined){
 		rootNodes = treeObj.getNodesByParam(""+pId_key+"", ""+root_pid+"", null);
 	}else{
 		rootNodes=treeNode;
 	}
		//循环判断该节点是否已加载子节点，是则进入下一次循环，否则加载子节点，确保加载子节点只加载一次，若加载多次会影响效率
    for(var i=0; i<rootNodes.length; i++){
        if(rootNodes[i].zAsync == false){
        	treeObj.reAsyncChildNodes(rootNodes[i], "",true);    
        }
        else continue;
    }//end for 
}//end func
function DAM_onloadZtree(){
	$.fn.zTree.init($("#"+treeId+""), settings);
	$("#"+searchInput+"").attr("placeholder","数据加载中，请稍等");
	$("#"+searchInput+"").attr("disabled",true);
	$("#"+searchId+"").attr("disabled",true);
	$("#"+searchId+"").bind("click").click(function(){
	    var value = $("#"+searchInput+"").val();
	    var treeObj = $.fn.zTree.getZTreeObj(""+treeId+"");
	    if( $.trim(value) == ""){
	        //显示所有隐藏节点
	        var hides = treeObj.getNodesByParam("isHidden", true);
	        if(hides.length>0){
	        	treeObj.showNodes(hides);
	        }
	        treeObj.expandAll(false);//折叠所有节点
	        return;
	    }//end if
	    //查找节点
	    var nodes = treeObj.getNodesByParamFuzzy(""+data_key+"", $.trim(value), null);
	    if(nodes.length>maxSearchResult){
	    	console.log("查询结果大于"+maxSearchResult+"，请完善查询条件!");
	    	var hides = treeObj.getNodesByParam("isHidden", true);
	        if(hides.length>0){
	        	treeObj.showNodes(hides);
	        }
	        treeObj.expandAll(false);//折叠所有节点
	    }else if(nodes.length<=0){
	    	console.log("查询结果不存在!");
	    }else{
	    	 //隐藏所有节点
		    var all = treeObj.transformToArray(treeObj.getNodes());
		    for (var i = 0; i < all.length; i++) {
		        treeObj.hideNode(all[i]);
		    }
	    	for (var i = 0; i < nodes.length; i++) {
		        treeObj.showNode(nodes[i]);//显示查到节点
		        //treeObj.showNode(nodes[i].getParentNode());//显示其父节点
		        showNodes(treeObj,nodes[i]);
		        if(!nodes[i].isParent){
		        	 treeObj.expandAll(true);//展开所有查询到的内容
		        }
		    }
	    }
	});
}

function DAM_onloadZtreeAsync(){
	$.fn.zTree.init($("#"+treeId+""), settings);
	$("#"+searchInput+"").attr("placeholder","请输入关键字查询");
	$("#"+searchId+"").bind("click").click(function(){
	    var value = $("#"+searchInput+"").val();
	    var treeObj = $.fn.zTree.getZTreeObj(""+treeId+"");
	    var nodes = treeObj.getSelectedNodes();
	    if(nodes.length>0){
	    	if(nodes[0].zAsync){
	    		 if( $.trim(value) == ""){
	    			 	//console.log("请输入需要所搜的内容");
	    			 	console.log("请输入需要搜索的内容");
	    			 	//显示所有隐藏节点
	    		        var hides = treeObj.getNodesByParam("isHidden", true);
	    		        if(hides.length>0){
	    		        	treeObj.showNodes(hides);
	    		        }
	    		        treeObj.expandAll(false);//折叠所有节点
	    		 }else{
				   //查找节点
				    var findNodes = treeObj.getNodesByParamFuzzy(""+data_key+"", $.trim(value), nodes[0]);
				    if(findNodes.length>0){
				    	//隐藏所有节点
					    var all = treeObj.transformToArray(treeObj.getNodes());
					    for (var i = 0; i < all.length; i++) {
					        treeObj.hideNode(all[i]);
					    }
					    for (var i = 0; i < findNodes.length; i++) {
					        treeObj.showNode(findNodes[i]);//显示查到节点
					        //treeObj.showNode(nodes[i].getParentNode());//显示其父节点
					        showNodes(treeObj,findNodes[i]);
					        //console.log(findNodes[i]);
					        if(!findNodes[i].isParent){
					        	treeObj.expandAll(true);//展开所有查询到的内容
					        }
					    }
				    }else{
				    	console.log("没有搜索到相关内容");
				    }
				    treeObj.selectNode(nodes[0]);
	    		 }
	    	}else{
	    		console.log("请等待节点加载完数据后，在进行搜索");
	    	}
	    	return;
	    }else{
	    	console.log("请选中父节点之后再进行查询");
	    	return;
	    }
	});
}


function hideDiv(){
	$("#"+showDiv+"").hide();
}

function showNodes(treeObj,node){
	if(node.getParentNode()!=null){
		 treeObj.showNode(node.getParentNode());//显示其父节点
		 showNodes(treeObj,node.getParentNode());
	}
}
//可重写
//可自己实现 获取到nodes后的业务
function openShowInputMethod(nodes){
	$("#"+showInput+"").val(nodes[0].name);
	$("#"+showInput+"").attr("attr_value",nodes[0].id);
}
$(function(){
	//console.log(isAutoAsync);
	//确定按钮绑定事件
	$("#"+okBtn+"").bind("click").click(function(){
		var treeObj = $.fn.zTree.getZTreeObj(""+treeId+"");
		if(isMulitSelect){
			var nodes = treeObj.getCheckedNodes(true);
			if(mulitNum==0){
				console.log("请先设置多选的最大值，建议不要超过100");
				return;
			}
			if(mulitNum>0){
				if(nodes.length>mulitNum){
					console.log("选择节点数大于"+mulitNum+",请重新选择!");
					return;
				}
			}
			console.log(nodes);
			if(nodes.length>0){
				var str="";
				var ids="";
				for(var i=0;i<nodes.length;i++){
					if(i==nodes.length-1){
						str=str+nodes[i].name;
						ids=ids+nodes[i].id;
					}else{
						str=str+nodes[i].name+",";
						ids=ids+nodes[i].id+",";
					}
				}
				$("#"+showInput+"").val(str);
		    	$("#"+showInput+"").attr("attr_value",ids);
			}else{
				console.log("多选框：请勾选节点");
				return;
			}
		}else{
			var nodes = treeObj.getSelectedNodes();
		    if(nodes.length>0){
		    	openShowInputMethod(nodes);
		    	//$("#"+showInput+"").val(nodes[0].name);
		    	//$("#"+showInput+"").attr("attr_value",nodes[0].id);
		    }else{
		    	console.log("请先选择节点");
		    	return;
		    }
		    console.log($("#"+showInput+"").attr("attr_value"));
		}
	    hideDiv();
	});
	//关闭按钮绑定事件
	$("#"+closeBtn+"").bind("click").click(function(){
		hideDiv();
	});
	
	//展示按钮绑定事件
	$("#"+showBtn+"").bind("click").click(function(){
		var obj = $("#"+showInput+"")[0];
		document.getElementById(''+showDiv+'').style.display="";
		document.getElementById(''+showDiv+'').style.left=obj.offsetLeft+'px';
		document.getElementById(''+showDiv+'').style.top=obj.offsetTop+ obj.offsetHeight+'px';
	});
	if(isAutoAsync){
		DAM_onloadZtree();
	}else{
		DAM_onloadZtreeAsync();
	}
	//点击需要回显的文本框 进行显示div操作
	$("#"+showInput+"").focus(function(){
		var obj = $("#"+showInput+"")[0];
		document.getElementById(''+showDiv+'').style.display="";
		document.getElementById(''+showDiv+'').style.left=obj.offsetLeft+'px';
		document.getElementById(''+showDiv+'').style.top=obj.offsetTop+ obj.offsetHeight+'px';
	});
});